package com.top.mall.main.home

import android.animation.Animator
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.module.lemlin.http.Status
import com.module.lemlin.image.loadCenterImage
import com.module.lemlin.owner.OwnerViewModeFragment
import com.top.mall.R
import com.top.mall.entity.CateList
import com.top.mall.jetpack.vm.HomeViewModel
import com.top.mall.main.goods.GoodsCategoryActivity
import com.top.mall.main.goods.GoodsHomeFragment
import com.top.mall.main.home.adapter.HomeBannerAdapter
import com.top.mall.main.home.adapter.HomeCateCursorAdapter
import com.top.mall.main.home.adapter.HomeCateGroupAdapter
import com.youth.banner.Banner
import com.youth.banner.indicator.RectangleIndicator
import kotlinx.android.synthetic.main.fragment_main_home.*
import kotlinx.android.synthetic.main.include_home_bar.*
import kotlinx.android.synthetic.main.include_home_heads.*
import kotlinx.android.synthetic.main.item_tab_home.view.*


class HomeFragment : OwnerViewModeFragment<HomeViewModel>(), AppBarLayout.OnOffsetChangedListener {

    private val homeBannerAdapter: HomeBannerAdapter = HomeBannerAdapter()
    private val homeCateGroupAdapter: HomeCateGroupAdapter = HomeCateGroupAdapter()
    private val homeCateCursorAdapter: HomeCateCursorAdapter = HomeCateCursorAdapter()

    override val layoutResId: Int
        get() = R.layout.fragment_main_home

    override fun viewModel(): HomeViewModel =
        createViewModel()

    override fun initView() {
        //为Toolbar添加状态栏高度
        BarUtils.addMarginTopEqualStatusBarHeight(toolbarHome)
        BarUtils.addMarginTopEqualStatusBarHeight(includeHomeBar)
        //为AppBar设置滑动监听
        appBarHome.addOnOffsetChangedListener(this)


        //为RecyclerView设内边距
        includeHomeHeads.setPadding(
            ConvertUtils.dp2px(0f), (ConvertUtils.dp2px(75f) + BarUtils.getStatusBarHeight()),
            ConvertUtils.dp2px(0f), ConvertUtils.dp2px(0f)
        )

//        //初始轮播视图
//        vpHomeBanner.apply {
//            indicator = RectangleIndicator(context)
//            setIntercept(false)
//        }.setOrientation(Banner.HORIZONTAL).setUserInputEnabled(true)
//            .adapter = homeBannerAdapter

        //初始分类视图
        vp2HomeCategory.apply {
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    homeCateCursorAdapter.selectedPosition = position
                }
            })
        }.adapter = homeCateGroupAdapter

        //初始指示器视图
        rvHomeIndicator.apply {
            layoutManager = LinearLayoutManager(requireContext()).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
        }.adapter = homeCateCursorAdapter


        tlHomeBody.apply {
            val tabs: MutableList<String> = mutableListOf<String>(
                "限时抢购", "天天特价", "商城推荐", "品牌特惠", "疯狂折扣", "买赠专场"
            )
            for ((index: Int, item: String) in tabs.withIndex()) addTab(newTab().apply {
                val view: View = LayoutInflater.from(requireContext())
                    .inflate(R.layout.item_tab_home, null)
                view.text_tab_home_name.text = item
                view.text_tab_home_sub.text = item
                if (index == 3) {
                    view.text_tab_home_name.setTextColor(resources.getColor(R.color.FF_FF8100))
                }
                customView = view
                tag = index
            })
        }.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) = Unit

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabSelected(tab: TabLayout.Tab?) {
                vpHomeBody.currentItem = tab?.position ?: 0
            }
        })

        vpHomeBody.apply {
            addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrollStateChanged(state: Int) = Unit

                override fun onPageScrolled(
                    position: Int, positionOffset: Float, positionOffsetPixels: Int
                ) = Unit

                override fun onPageSelected(position: Int) {
                    tlHomeBody.getTabAt(position)?.select()
                }
            })
        }.adapter = object : FragmentStatePagerAdapter(
            childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItem(position: Int): Fragment =
                GoodsHomeFragment.newInstance(position + 2)

            override fun getCount(): Int = 6

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {}
        }


    }


    // FAB移出屏幕动画（隐藏动画）
    private fun animateOut(fab: ImageView) {
        val layoutParams =
            fab.layoutParams as FrameLayout.LayoutParams
        val rightMargin = layoutParams.rightMargin
        fab.animate().translationX(fab.width + rightMargin.toFloat())
            .setInterpolator(LinearInterpolator()).setListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(animation: Animator?) {

                }

                override fun onAnimationEnd(animation: Animator?) {
                    fab.visibility = View.GONE
                }

                override fun onAnimationCancel(animation: Animator?) {

                }

                override fun onAnimationStart(animation: Animator?) {

                }
            }).start()
    }

    // FAB移入屏幕动画（显示动画）
    private fun animateIn(fab: ImageView) {
        fab.visibility = View.VISIBLE
        fab.animate().translationX(0f).setInterpolator(LinearInterpolator()).withLayer()
            .setListener(null).start()
    }


    override fun initData() {


        viewModel.homeIndex()
    }

    override fun initViewMode() {
        viewModel.homeIndexLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe

            //初始轮播视图
            vpHomeBanner.apply {
                indicator = RectangleIndicator(context)
                setIntercept(false)
            }.setOrientation(Banner.HORIZONTAL).setUserInputEnabled(true)
                .adapter = homeBannerAdapter
            homeBannerAdapter.setDatas(data.banner)

            val category = mutableListOf<MutableList<CateList>>()
            val cursors = mutableListOf<Int>()
            val catSize = data.cat_list.size
            for (index in 0..catSize / 10) {
                val startIndex = (index * 10)
                val endIndex = if (catSize < ((index + 1) * 10))
                    catSize else (index + 1) * 10
                val category1 = data.cat_list.slice((startIndex until endIndex))
                    .toMutableList()
                category.add(category1)
                cursors.add(index)
            }
            homeCateGroupAdapter.setNewInstance(category)
            homeCateCursorAdapter.setNewInstance(cursors)

            ivHomeCapsule.loadCenterImage(data.activity.image)

        })
    }

    override fun onResume() {
        super.onResume()
        vpHomeBanner.start()
    }

    override fun onPause() {
        super.onPause()
        vpHomeBanner.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        vpHomeBanner.destroy()
    }

    public var alphaStatus: Int = 0

    //搜索布局展开时顶部距离
    private val searchMaxTopMargin: Float =
        ConvertUtils.dp2px(45f).toFloat()

    //搜索布局关闭时顶部距离
    private val searchMinTopMargin: Float =
        ConvertUtils.dp2px(6.5f).toFloat()

    //搜索布局展开时的宽度
    private val searchMaxWidth: Float =
        (ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(26f)).toFloat()

    //搜索布局关闭时的宽度
    private val searchMinWidth: Float =
        (ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(55f)).toFloat()
    private val alphaMaxHeight: Float =
        ConvertUtils.dp2px(10f).toFloat()

    override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {


        if (verticalOffset * -1 == appBarHome.totalScrollRange) {
//            animateOut(ivHomeFloat)
            tlHomeBody.setBackgroundResource(R.color.colorWhite)
        } else {
            tlHomeBody.setBackgroundResource(R.color.transparent)
//            if (ivHomeFloat.visibility == View.GONE) {
//                animateIn(ivHomeFloat)
//            }
        }

        val offset: Float = verticalOffset * -0.65f

        var searchNewTopMargin: Float = searchMaxTopMargin - (offset * 1.5f)
        var searchNewWidth: Float = searchMaxWidth - (offset * 1.15f)
        val alphaNewHeight: Float = alphaMaxHeight - (offset * 0.5f)
        //处理布局的边界问题
        if (searchNewTopMargin < searchMinTopMargin) {
            searchNewTopMargin = searchMinTopMargin
        }
        if (searchNewWidth < searchMinWidth) {
            searchNewWidth = searchMinWidth
        }

        var alpha1: Float = (255 * alphaNewHeight / alphaMaxHeight)
        if (alpha1 < 0)
            alpha1 = 0f
        tvHomeLocal.setTextColor(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )
        ivHomeLocalNext.setColorFilter(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )
        ivHomeScan.setColorFilter(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )
        ivHomeMsg.setColorFilter(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )

//        for ((key,value) in homeLabelAdapter.itemViews){
//            value.setTextColor(
//                Color.argb(alpha1.toInt(), 255, 255,255)
//            )
//            value.background.alpha = alpha1.toInt()
//        }

        var alpha2: Float =
            255 * (alphaMaxHeight - alphaNewHeight) / alphaMaxHeight
        if (alpha2 > 255)
            alpha2 = 255f
        ivHomeLocal.setColorFilter(
            Color.argb(alpha2.toInt(), 0, 0, 0)
        )
        clHomeSearch.setBackgroundColor(
            Color.argb(alpha2.toInt(), 255, 255, 255)
        )
        flHomeSearch.setBackgroundResource(
            if (alpha2 > 150) R.drawable.bg_radius_20dp_milky else R.drawable.bg_radius_20dp_white
        )
        BarUtils.setStatusBarColor(
            requireActivity(), Color.argb(alpha2.toInt(), 255, 255, 255)
        )
        BarUtils.setStatusBarLightMode(
            requireActivity(), alpha2 > 180
        )
        alphaStatus = alpha2.toInt()

        flHomeSearch.layoutParams =
            (flHomeSearch.layoutParams as ViewGroup.MarginLayoutParams).apply {
                topMargin = searchNewTopMargin.toInt()
                width = searchNewWidth.toInt()
            }
    }


    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }
}